package com.xxb.system.upload.rest;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.xxb.common.result.R;
import com.xxb.system.upload.config.MinIOConfig;
import com.xxb.system.upload.service.impl.MinIoUploadServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author RenGaoshuai
 * @date 2023/7/25 14:54
 * @description
 */
@RestController
@Slf4j
public class MinioUploadController {
    @Autowired
    private MinIoUploadServiceImpl minIoUploadService;
    @Autowired
    private MinIOConfig minIOConfig;

    @PostMapping("/upload/minio/file")
    public R<Map<String, Object>> upload(@RequestParam(value = "file") MultipartFile file,
                    HttpServletRequest request) throws Exception {

        // 指定一个业务的目录进行文件的存储
        String dir = request.getParameter("dir");
        if (StrUtil.isEmpty(dir)) {
            // 如果不指定默认是course
            dir = "course";
        }
        // 构建日期目录
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String datePath = dateFormat.format(new Date());

        // 获取文件的原始名字
        String originname = file.getOriginalFilename();
        // 文件更名，防止多个用户上传相同的文件进行冲突，所以要更名
        String filename = IdUtil.simpleUUID();

        String suffix = originname.substring(originname.lastIndexOf("."));
        String newName = filename + suffix;
        String fileUrl = dir + "/" + datePath + "/" + newName;

        if (!minIoUploadService.isObjectExist(minIOConfig.getBucketName(),fileUrl)) {
            //文件不存在
            minIoUploadService.createDir(minIOConfig.getBucketName(),fileUrl);
        }
        //上传
        minIoUploadService.uploadFile(minIOConfig.getBucketName(),fileUrl,file.getInputStream());

        //组装返回参数
        String imgUrl = minIOConfig.getFileHost()
                + "/"
                + minIOConfig.getBucketName()
                + "/"
                + fileUrl;
        Map<String, Object> map = new HashMap<>();
        map.put("url", imgUrl);
        map.put("size", file.getSize() + "");
        map.put("ext", suffix);
        map.put("filename", originname);
        map.put("newname", filename);
        map.put("rpath", fileUrl);
        return R.ofSuccess(map);
    }
}
